/*
 * $Id: serial.h,v 1.14 2005-12-28 11:53:24 bacon Exp $
 */

#ifndef _XP_NET_SERIAL_H_
#define _XP_NET_SERIAL_H_

#include <xp/types.h>
#include <xp/macros.h>
#include <xp/bas/time.h>

#ifdef _WIN32
	#include <windows.h>
#else
	#include <termios.h>
	#include <sys/ioctl.h>
#endif

#ifdef _WIN32
	typedef HANDLE xp_serial_hnd_t;
	#define XP_SERIAL_INVALID_HANDLE (INVALID_HANDLE_VALUE)
#else
	typedef int xp_serial_hnd_t;
	#define XP_SERIAL_INVALID_HANDLE (-1)
#endif

typedef struct xp_serial_t xp_serial_t;

struct xp_serial_t
{
	xp_serial_hnd_t handle;

#ifdef _WIN32
	DCB __orgattr;
#else
	struct termios __orgattr;
#endif
	xp_bool_t __dynamic;
};

enum {
#ifdef _WIN32
	XP_SERIAL_PARITY_NONE  = NOPARITY,
	XP_SERIAL_PARITY_ODD   = ODDPARITY,
	XP_SERIAL_PARITY_EVEN  = EVENPARITY,
	XP_SERIAL_PARITY_MARK  = MARKPARITY,
	XP_SERIAL_PARITY_SPACE = SPACEPARITY
#else
	XP_SERIAL_PARITY_NONE,
	XP_SERIAL_PARITY_ODD,
	XP_SERIAL_PARITY_EVEN,
	XP_SERIAL_PARITY_MARK,
	XP_SERIAL_PARITY_SPACE
#endif
};

enum {
#ifdef _WIN32
	XP_SERIAL_STOPBITS_ONE  = ONESTOPBIT,
	XP_SERIAL_STOPBITS_ONE5 = ONE5STOPBITS,
	XP_SERIAL_STOPBITS_TWO  = TWOSTOPBITS
#else
	XP_SERIAL_STOPBITS_ONE  = 1,
	XP_SERIAL_STOPBITS_ONE5 = 1,
	XP_SERIAL_STOPBITS_TWO  = 2
#endif
};

enum {
	XP_SERIAL_FLOWCONTROL_NONE = 0,
	XP_SERIAL_FLOWCONTROL_HARDWARE = 1,
	XP_SERIAL_FLOWCONTROL_SOFTWARE = 2
};

enum {
	XP_SERIAL_DRAIN = 1
};

enum 
{
	XP_SERIAL_DTR = 1,
	XP_SERIAL_RTS = 2,
	XP_SERIAL_DSR = 4,
	XP_SERIAL_CTS = 8
};

#ifdef __cplusplus
extern "C" {
#endif

xp_serial_t* xp_serial_open (
    xp_serial_t* serial, const xp_char_t* name, int baud_rate,
	int parity, int data_bits, int stop_bits, int flow_control);
int xp_serial_close (xp_serial_t* serial);

xp_ssize_t xp_serial_send (
	xp_serial_t* serial, const void* msg, xp_size_t len, xp_time_t timeout);
xp_ssize_t xp_serial_sendall (
	xp_serial_t* serial, const void* msg, xp_size_t len, xp_time_t timeout);

xp_ssize_t xp_serial_recv (
	xp_serial_t* serial, void* buf, xp_size_t len, xp_time_t timeout);
xp_ssize_t xp_serial_recvall (
	xp_serial_t* serial, void* buf, xp_size_t len, xp_time_t timeout);

int xp_serial_flush_input (xp_serial_t* serial);
int xp_serial_flush_output (xp_serial_t* serial);

int xp_serial_break (xp_serial_t* serial, xp_time_t duration);
int xp_serial_get_status (xp_serial_t* serial, int* status);
int xp_serial_set_status (xp_serial_t* serial, int status);

/*
int xp_serial_setdtr (xp_serial_t* serial);
int xp_serial_clrdtr (xp_serial_t* serial);
int xp_serial_setrts (xp_serial_t* serial);
int xp_serial_clrrts (xp_serial_t* serial);
*/

#ifdef __cplusplus
}
#endif

#endif
